const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: undefined,
    name: "",
    spec: "",
    price: "",
    incentiveFees: "",
    showPicker: false,
    showDetail: false,
    // 物料列表
    materielList: [],
    result: [],
    //多选选中的结果
    selectedList: [],
    packMateriels: [],
    tips: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getMateriel().then((res) => {
      this.setData({
        materielList: res
      });

      // 是否有详情
      let id = options.id;
      if (id) {
        wx.setNavigationBarTitle({
          title: "修改包装"
        });
        this.setData({
          id
        });
        this.getDetails(id);
      }
    });
  },

  // 提交
  onSuccess() {
    const { name, spec, price, incentiveFees, selectedList } = this.data;

    if (wx.$isNull(name)) {
      return wx.showToast({
        icon: "error",
        title: "请输入正确名称"
      });
    }

    if (wx.$isNull(spec)) {
      return wx.showToast({
        icon: "error",
        title: "请输入装货规格"
      });
    }

    if (wx.$isNull(price)) {
      return wx.showToast({
        icon: "error",
        title: "请输入包装单价"
      });
    }

    if (wx.$isNull(incentiveFees)) {
      return wx.showToast({
        icon: "error",
        title: "请输入小工费用"
      });
    }

    let params = {
      id: this.data.id,
      companyId: app.globalData.userInfo.companyData.companyId,
      name,
      spec,
      incentiveFees: wx.$getFen(incentiveFees),
      price: wx.$getFen(price),
      packMateriels: selectedList.map((item) => {
        return {
          count: item.count,
          materielId: item.id,
          id: item.relationId
        };
      })
    };
    this.submit(params);
  },

  // 新增包装
  submit(params) {
    wx.showLoading({
      title: "添加中..."
    });
    let title = "添加成功";
    let api = "addPack";
    if (this.data.id) {
      api = "editPack";
      title = "修改成功";
    }
    wx.$apis[api](params).then((res) => {
      wx.setStorage({
        key: "back",
        data: 1,
        success: () => {
          wx.showToast({
            title,
            icon: "success",
            duration: 1000
          }).then(() => {
            setTimeout(() => {
              wx.navigateBack();
            }, 1000);
          });
        }
      });
    });
  },

  // 获取包装及物料详情
  getDetails(id) {
    wx.showLoading({
      title: "查询中..."
    });
    wx.$apis.getPackAndMaterielDetail(id).then((res) => {
      if (res.data) {
        const { name, price, spec, incentiveFees, tmuId, packMateriels } = res.data;
        let materielList = this.data.materielList;
        this.setData({
          incentiveFees: wx.$getYuan(incentiveFees),
          showDetail: true,
          name,
          price: wx.$getYuan(price),
          spec,
          result: packMateriels.map((item) => {
            let Index = materielList.findIndex((m) => m.id == item.materielId);
            return materielList[Index].name;
          }),
          selectedList: packMateriels.map((item) => {
            let Index = materielList.findIndex((m) => m.id == item.materielId);
            return {
              name: materielList[Index].name,
              count: item.count,
              // 包装关联物料ID
              relationId: item.id,
              // 包装id
              packId: item.packId,
              // 物料id
              id: item.materielId
            };
          })
        });
      }
    });
  },

  // 获取物料
  getMateriel() {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: "查询中..."
      });
      wx.$apis
        .getMateriel(app.globalData.userInfo.companyData.companyId)
        .then((res) => {
          if (res.data) {
            resolve(res.data);
          } else {
            reject();
          }
        })
        .catch((err) => {
          reject();
        });
    });
  },

  // 步进器改变
  onStepChange(event) {
    const Index = event.target.dataset.index;
    let result = this.data.result;
    let selectedList = this.data.selectedList;
    let count = event.detail;
    selectedList[Index].count = count;
    this.setData({
      selectedList
    });
    if (event.detail === 0) {
      result.splice(index, 1);
      selectedList.splice(index, 1);
      // 删除当前的一条
      this.setData({
        selectedList,
        result
      });
    }
    if (this.data.selectedList.length === 0) {
      this.setData({
        showDetail: false
      });
    }
  },
  onSelectChange() {
    this.setData({
      showPicker: true
    });
  },
  onCancelMateriel() {
    this.setData({
      showPicker: false
    });
  },
  onConfirmMateriel() {
    let selectedList = [];
    let materielList = this.data.materielList;
    this.data.result.forEach((item) => {
      let Index = materielList.findIndex((m) => m.name == item);
      if (Index > -1) {
        let obj = {
          id: materielList[Index].id,
          name: item,
          count: 1
        };
        selectedList.push(obj);
      }
    });
    this.setData({
      showDetail: selectedList.length ? true : false,
      selectedList,
      showPicker: false
    });
  },
  onCheckBoxChange(event) {
    this.setData({
      result: event.detail
    });
    console.log("result", this.data.result);
  },

  toggle(event) {
    const { index } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  }
});
